package com.fh.fruit.controller.basearea;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.fruit.entity.basearea.BaseArea;
import com.fh.fruit.service.basearea.BaseAreaManager;
import com.fh.fruit.service.baseareagoods.AreaGoodsCountManager;
import com.fh.fruit.service.plantbase.PlantBaseManager;
import com.fh.util.AppUtil;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.Jurisdiction;
import com.fh.util.PageData;
/**
 * 种植区域
 * @author Administrator
 * @version 2017.11.30 15:39
 */
@Controller
@RequestMapping(value = "/basearea")
public class BaseAreaController extends BaseController {
	private String menuUrl = "basearea/list.do"; //种植区域列表(权限用)
	
	@Resource(name = "baseAreaService")
	private BaseAreaManager baseAreaService;
	@Resource(name = "plantBaseService")
	private PlantBaseManager plantBaseService;
	@Resource(name = "areaGoodsCountService")
	private AreaGoodsCountManager areaGoodsCountService;

	/**
	 * 显示区域列表
	 * 
	 * @param page 页面参数
	 * @param httpSession httpSession
	 * @return ModelAndView
	 * @throws Exception Exception
	 */
	@RequestMapping(value = "/list")
	public ModelAndView baseAreasList(Page page, HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String name = pd.getString("name"); // 关键词检索条件
		if (StringUtils.isNotEmpty(name)) {
			pd.put("name", name.trim());
		}
		page.setPd(pd);
		List<BaseArea> baseAreasList = baseAreaService.listBaseAreas(page); // 列出区域列表
		mv.setViewName("farm/basearea/baseArea_list");
		mv.addObject("baseAreasList", baseAreasList);
		mv.addObject("pd", pd);
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;
	}

	/**
	 * 去新增种植区域
	 * @param page 页面参数
	 * @return ModelAndView
	 * @throws Exception Exception
	 */
	@RequestMapping(value = "/goAddP")
	public ModelAndView goAddP(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String state = pd.getString("state");
		String baseName = pd.getString("baseName");
		String baseId = pd.getString("baseId");
		BaseArea basearea = new BaseArea();
		basearea.setBaseId(Integer.valueOf(baseId));
		basearea.setBaseName(baseName);
		mv.setViewName("farm/basearea/baseArea_edit");
		mv.addObject("msg", "saveP");
		mv.addObject("state", state);
		mv.addObject("pd", pd);
		mv.addObject("basearea", basearea);
		return mv;
	}

	/**
	 * 去修改区域信息
	 * 
	 * @param page 页面参数
	 * @return ModelAndView
	 * @throws Exception Exception
	 */
	@RequestMapping(value = "/goEditP")
	public ModelAndView goEditP(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String state = pd.getString("state");
		BaseArea basearea = baseAreaService.findById(pd);
		mv.setViewName("farm/basearea/baseArea_edit");
		mv.addObject("pd", pd);
		mv.addObject("state", state);
		mv.addObject("msg", "editP");
		mv.addObject("basearea", basearea);
		return mv;
	}
	
	/**
	 * 编辑保存区域信息
	 * 
	 * @return ModelAndView
	 * @throws Exception Exception
	 */
	@RequestMapping(value = "/editP")
	public ModelAndView editP() throws Exception {
		// 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "修改种植区域信息");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		try {
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("operatorId", user.getUSER_ID()); // 修改人
			pd.put("updateTime", DateUtil.getTime()); // 修改时间
			int rec = baseAreaService.updateBaseAreas(pd);
			if (rec <= 0) {
				mv.addObject("msg", "失败，操作数据不存在！");
			}
		} catch (Exception e) {
			mv.addObject("msg", "failed");
			logger.error(e.toString(), e);
		}
		logAfter(logger);
		mv.setViewName("save_result");
		return mv;
	}
	/**
	 * 新增保存区域信息
	 * 
	 * @return ModelAndView
	 * @throws Exception Exception
	 */
	@RequestMapping(value = "/saveP")
	public ModelAndView saveP() throws Exception {
		// 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "新增种植区域信息");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		try {
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("operatorId", user.getUSER_ID()); // 操作人
			pd.put("createTime", DateUtil.getTime()); // 创建时间
			baseAreaService.saveBaseAreas(pd);
		} catch (Exception e) {
			mv.addObject("msg", "failed");
			logger.error(e.toString(), e);
		}
		logAfter(logger);
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 删除区域
	 * 
	 * @param requset requset
	 * @return String
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteP")
	@ResponseBody
	public String deleteP(HttpServletRequest requset) {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "删除种植区域");
		PageData pd = this.getPageData();
		String baseAreaId = pd.getString("ids"); // 区域id
		if (StringUtils.isNotEmpty(baseAreaId)) {
			pd.put("baseAreaId", baseAreaId.trim());
		} else {
			//03：区域ID不能为空
			return "03";
		}
		try {
			//区域下有商品时不能删除区域
			if (areaGoodsCountService.selectTotalAreaGoods(pd) > 0) {
				//02：区域下存在商品
				return "02";
			}
			int rec = baseAreaService.deleteBaseAreas(pd);
			if (rec > 0) {
				//01：删除成功
				return "01";
			} else {
				//00：删除失败
				return "00";
			}			
		} catch (Exception e) {
			logger.error(e.toString(), e);
			return "failed";
		}
	}

	/**
	 * 判断区域名称或者编码是否存在
	 * 
	 * @return Object
	 */
	@RequestMapping(value = "/hasU")
	@ResponseBody
	public Object hasU() {
		String result = "success";
		PageData pd = this.getPageData();
		try {
			List<PageData> list = baseAreaService.findByNameOrCode(pd);
			if (list != null && list.size() > 0) {
				result = "error";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("result", result);
		return AppUtil.returnObject(new PageData(), map);
	}

	/**
	 * 判断区域者编码是否存在
	 * 
	 * @return Object
	 */
	@RequestMapping(value = "/hasN")
	@ResponseBody
	public Object hasN() {
		String result = "success";
		PageData pd = this.getPageData();
		try {
			List<PageData> list = baseAreaService.findByNameOrCode(pd);
			if (list != null && list.size() > 0) {
				result = "error";
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("result", result);
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 显示种植基地列表ztree
	 * 
	 * @param model model
	 * @param id id
	 * @return ModelAndView
	 * @throws Exception Exception
	 */
	@RequestMapping(value = "/listAllClassify")
	public ModelAndView listAllClassify(Model model, String id) throws Exception {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("farm/basearea/plantbase_ztree");
		return mv;
	}

	/**
	 * 异步加载树节点
	 * @param request request
	 * @param response response
	 */
	@RequestMapping("/asynTree")
	public void asynTree(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		response.setCharacterEncoding("UTF-8"); 
		logBefore(logger, "加载种植基地");		
		String id = request.getParameter("id");
        List<PageData> lists = new ArrayList<>();
        List<PageData> list = null;
        try {
			out = response.getWriter();
			if ("0".equals(id)) {
				list = plantBaseService.synTree(Integer.parseInt(id));
			} else {
				list = new ArrayList<PageData>();
			}
			for (int i = 0; i < list.size(); i++) {
				@SuppressWarnings("unchecked")
				HashMap<String, Object>  maps = list.get(i); 
				PageData pd = new PageData();
				pd.put("id", maps.get("id"));
				pd.put("name", maps.get("name"));
				pd.put("isParent", true);
				pd.put("open", false);
				pd.put("url", "basearea/list.do?baseId=" + maps.get("id") + "&baseName=" + maps.get("name"));
				pd.put("target", "treeFrame");
				lists.add(i, pd);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
        logAfter(logger);
		out.write(JSON.toJSONString(lists));
	}
}
